package cn.devcat.sso.service.impl;

import cn.devcat.sso.config.exception.TaskProjectException;
import cn.devcat.sso.entity.DevcatTaskProject;
import cn.devcat.sso.entity.PageData;
import cn.devcat.sso.entity.SearchCommonParam;
import cn.devcat.sso.mapper.DevcatTaskProjectMapper;
import cn.devcat.sso.service.IDevcatTaskProjectService;
import cn.devcat.sso.service.IDevcatTaskService;
import cn.devcat.sso.util.PageHelperUtil;
import cn.devcat.sso.util.UserUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DevcatTaskProjectServiceImpl extends ServiceImpl<DevcatTaskProjectMapper, DevcatTaskProject> implements IDevcatTaskProjectService {

  @Autowired
  IDevcatTaskService taskService;

  @Autowired
  UserUtil userUtil;

  @Override
  public void addProject(DevcatTaskProject project) {
    project.setCreateTime(LocalDateTime.now());
    project.setUserId(userUtil.getUserByRequest().getId());
    long count = count(new QueryWrapper<DevcatTaskProject>().eq("project_name", project.getProjectName()));
    if(count == 0){
      save(project);
    }else{
      throw new TaskProjectException("已存在相同名称的项目");
    }
  }

  @Transactional
  @Override
  public void delProject(List<Long> ids) {
    //首先删除关联的任务
    taskService.delTaskByProjectIds(ids);
    removeBatchByIds(ids);
  }

  @Override
  public void setProject(DevcatTaskProject project) {
    long count = count(new QueryWrapper<DevcatTaskProject>().ne("id", project.getId()).eq("project_name", project.getProjectName()));
    if(count>0){
      throw new TaskProjectException("已存在该项目名");
    }
    updateById(project);
  }

  @Override
  public PageData<DevcatTaskProject> getProject(SearchCommonParam param) {
    PageHelperUtil.handle(param);
    QueryWrapper<DevcatTaskProject> wrapper = new QueryWrapper<>();
    wrapper.eq("user_id", userUtil.getUserByRequest().getId());
    if(StringUtils.isNotEmpty(param.getKeyword())){
      wrapper.like("project_name",param.getKeyword());
    }
    wrapper.orderByDesc("create_time");
    List<DevcatTaskProject> list = list(wrapper);
    return PageHelperUtil.makePageData(new PageInfo<>(list));
  }
}
